package controller;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.RequestDispatcher;
import javax.servlet.Servlet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bizlogic.UserManager;

import model.UserDTO;
import model.UserSearchNameDTO;

/**
 * Servlet implementation class StaffProcessServlet
 */
@WebServlet("/StaffProcessServlet")
public class StaffProcessServlet extends HttpServlet implements Servlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
	public StaffProcessServlet() {
		super();
	}   	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}  	
	
	/* (non-Java-doc)
	 * @see javax.servlet.http.HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		processRequest(request, response);
	}   
	
	private void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		UserManager um = new UserManager();
		UserDTO staff = new UserDTO();
		
		String ins = (String) request.getParameter("ins");
		if (ins.equalsIgnoreCase("true")) {
		staff.setUsername(request.getParameter("username"));
		staff.setPassword("123pa$$word");
		staff.setRole(request.getParameter("role"));
		staff.setContactNo(new Integer(request.getParameter("contactNo")));
		staff.setEmail(request.getParameter("email"));
		staff.setReportTo(new Integer(request.getParameter("reportTo")));
		int userid = um.insertUser(staff);
		int userId = userid;
//		UserDTO uso = new UserDTO();
		UserDTO userlist = um.findbyId(userId);
		request.setAttribute("staff", userlist);
		RequestDispatcher rd = request.getRequestDispatcher("/ManageStaff.jsp");
		rd.forward(request, response);
		
		} else {
			staff.setRole(request.getParameter("role"));
			staff.setContactNo(new Integer(request.getParameter("contactNo")));
			staff.setEmail(request.getParameter("email"));
			staff.setReportTo(new Integer(request.getParameter("reportTo")));
			staff.setUserId(Integer.parseInt(request.getParameter("userId")));
			staff.setUsername(request.getParameter("username"));
			um.updateUser(staff);
		RequestDispatcher rd = request.getRequestDispatcher("/staffsearch");
		rd.forward(request, response);
		}
		
	}

}
